package com.hxkj.client.service.taglib.directive;

import com.hxkj.client.service.ColumnServiceClient;
import com.hxkj.client.service.ContentMappingServiceClient;
import com.hxkj.domain.context.EnvironmentContextHolder;
import com.hxkj.domain.po.*;
import com.hxkj.utils.TemplateModelUtils;
import com.platform.common.domain.result.ResultDataStruct;
import com.platform.common.domain.result.ResultPageStruct;
import com.platform.common.domain.to.PageTo;
import freemarker.core.Environment;
import freemarker.template.TemplateDirectiveBody;
import freemarker.template.TemplateException;
import freemarker.template.TemplateModel;
import lombok.extern.log4j.Log4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.io.Writer;
import java.util.*;

/**
 * @ClassName ColumnPageArticleList 分类的分页文章列表
 * @Description TODO
 * @Author Mr.zheng
 * @Date 2018/9/29 9:02
 * @Version 1.0
 */
@Component
@Log4j
public class ColumnPageArticleListDirective extends AbstractDirective {

    @Autowired
    private ColumnServiceClient columnServiceClient;

    @Autowired
    private ContentMappingServiceClient contentMappingServiceClient;


    /**
     * 输入参数，分类ID
     */
    public static final String COLUMN_ID = "columnId";
    /**
     * 输入参数，站点ID
     */
    public static final String SITE_ID = "siteId";

    /**
     * 输入参数，获取条数
     */
    public static final String COUNT = "count";


    /**
     * 当前分类信息
     */
    public static final String COLUMN_THIS = "column";

    /**
     * 当前分类的文章列表
     */
    public static final String COLUMN_ARTICLE_LIST = "articleList";


    @Override
    public void execute(Environment env, Map params, TemplateModel[] loopVars, TemplateDirectiveBody body) throws TemplateException, IOException {
        try {
            //Mr.zheng:获取参数
            Long columnIdEnv = TemplateModelUtils.converLong(env.getVariable("columnId"));
            Long columnId = super.getLong(COLUMN_ID, params) == null ? columnIdEnv : super.getLong(COLUMN_ID, params);
            Long siteId = super.getLong(SITE_ID, params) == null ? (Long) getCustomAttrbute(env, SITE_ID) : super.getLong(SITE_ID, params);
            //Mr.zheng:默认取5条文章
            int count = super.getInt(COUNT, params) == null ? -1 : super.getInt(COUNT, params);
            int pageNum = (Integer) getCustomAttrbute(env, "pageNum") == null ? 1 : (Integer) getCustomAttrbute(env, "pageNum");
            String note = super.getNote(env);
            if (columnId == null) {
                log.info("分类ID为空");
            }

            Column column = new Column();
            column.setColumnId(columnId);
            column.setSiteId(siteId);
            //Mr.zheng:封装当前选中的分类信息
            column = columnServiceClient.getColumn(column);

            column.setCount(count);
            ContentMapping contentMapping = new ContentMapping();
            contentMapping.setColumnId(columnId);

            List<ContentMapping> contentMappingList = new ArrayList<>();
            if (column.getContentStatus() == 1) {
                ResultDataStruct<List<ContentMapping>> result = contentMappingServiceClient.getContentMappingList(contentMapping);
                if (result.getData() != null) {
                    contentMappingList = result.getData();
                }
            }

            Map<String, Object> enviroment = EnvironmentContextHolder.getEnvironment();
            Map<Long, String> siteCtxMap = (Map<Long, String>) enviroment.get("siteCtxMap");
            WebsiteAddr websiteAddr = getWebSiteAddr(siteId);
            if (StringUtils.isNotBlank(note)) {
                if (column == null) column = new Column();
                column.setManuscriptPath(websiteAddr.getIpAdd() + column.getManuscriptPath());
            }else{
                // 静态文件分类链接加前缀
                String urlContext = siteCtxMap.get(column.getSiteId());
                if(StringUtils.isNotBlank(urlContext)) {
                    column.setManuscriptPath(urlContext + column.getManuscriptPath());
                }
            }
            env.setVariable(COLUMN_THIS, DefaultObjectWrapperBuilderFactory.getDefaultObjectWrapper().wrap(column));
            String path = "";
            if (column != null && StringUtils.isNotBlank(column.getManuscriptPath())) {
                path = column.getManuscriptPath().split("_")[0];
            }
            ResultPageStruct<Article> resultPageStruct = getArticleResultPageStruct(pageNum, column);
            PageTo pageInfo = resultPageStruct.getPageInfo();
            pageInfo.setCondition(path);
            List<Article> articleList = resultPageStruct.getData();

            if (contentMappingList != null && contentMappingList.size() > 0) {
                for (Article art : articleList) {
                    setContentMap(art, contentMappingList);
                }
            }

            if (StringUtils.isNotBlank(note)) {
                for (Article article : articleList) {
                    article.setManuscriptPath(websiteAddr.getIpAdd() + article.getManuscriptPath());
                }
            }else {
                // 静态文件文章链接加前缀
                for (Article item : articleList) {
                    String urlContext = siteCtxMap.get(item.getSiteId());
                    if(StringUtils.isNotBlank(urlContext)) {
                        item.setManuscriptPath(urlContext + item.getManuscriptPath());
                    }
                }
            }

            env.setVariable(COLUMN_ARTICLE_LIST, DefaultObjectWrapperBuilderFactory.getDefaultObjectWrapper().wrap(articleList));




            String userToken = super.getUserToken(env);
            Writer out = env.getOut();
            if (body != null) {
                if (StringUtils.isEmpty(note)) {
                    body.render(env.getOut());
                } else {
                    Map<String, String> maps = new LinkedHashMap<>();
                    try {
                        super.print(body, maps, env, userToken, params);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            } else {
                throw new RuntimeException("分类所在模板至少要加一个空格");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
